package com.hooview.quartz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hooview.api.entity.CurrencyExchange;
import com.hooview.api.service.CurrencyExchangeService;
import com.hooview.utils.HttpClientUtils;
import com.hooview.utils.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiaoemo on 2017/11/23.
 *
 * @author xiaoemo
 */
@Component
public class CurrencyRateQuartzAction {
    @Resource
    private CurrencyExchangeService currencyExchangeService;

    /**
     * 定时获取API数据任务
     */

    //@Scheduled(cron = "0 0 0/1 * * ?") //每5分钟执行一次
    public void rateTask() throws Exception {
        double rate = getCurrenRate2("USD", "CNY");
        if (rate > 0) {
            CurrencyExchange currencyExchange = new CurrencyExchange();
            currencyExchange.setRate(rate);
            currencyExchange.setScur("USD");
            currencyExchange.setTcur("CNY");
            currencyExchangeService.insert(currencyExchange);
        }
    }


    public static double getCurrenRate2(String scur, String tcur) {
        String host = "http://jisuhuilv.market.alicloudapi.com";
        String path = "/exchange/convert";
        String method = "GET";
        String appcode = "7bc7c8a806a2477f84466ab8da7765fe";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("amount", "1");
        querys.put("from", scur);
        querys.put("to", tcur);


        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            HttpEntity entity = response.getEntity();
            String json = EntityUtils.toString(entity);
            JSONObject object = JSON.parseObject(json);
            if (object.getString("status").equalsIgnoreCase("0")) {
                return object.getJSONObject("result").getFloat("rate");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
